import { getQueryString } from '@/utils/util';
import { post2Server } from '@/services/api';
import router from 'umi/router';

const redirect_uri = encodeURI("https://dbwxtest.cmbc.com.cn/weixin/static/game/index.html");
const appid = "wx6ecf5cfa0d0a6731";

export default {

  state: {
    userInfo: {},
  },

  reducers: {
    saveUser(state, {payload}){
      return {
        ...state,
        userInfo: payload,
      }
    }
  },

  effects: {
    *fetchUser(payload, { call, put }){
      let code = getQueryString("code");
      if(!code){
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
        return;
      }
      const response = yield call(post2Server, 'GMLogin.do', {
        Code: code,
        TestFlg: process.env.NODE_ENV === "development" ? true : false,
      });
      if(response){
        yield put({
          type: 'saveUser',
          payload: response,
        });
        router.replace('/main');
      }
    }
  },

  subscriptions: {
    setup({dispatch}){
      dispatch({
        type: 'fetchUser'
      });
    }
  }

}
